package com.example.spirngsecurityverifycode.fiflter;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: zjh
 * @Date: 2025/9/7 - 09 - 07 - 23:44
 * @Description: com.example.spirngsecurityverifycode.fiflter
 * @version: 1.0
 */
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if ( !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String verify = request.getParameter("kaptcha");
        String kaptcha = (String) request.getSession().getAttribute("kaptcha");
        if (verify.isEmpty()||kaptcha.isEmpty() || !verify.equalsIgnoreCase(kaptcha)){
            throw new AuthenticationServiceException("验证码错误");
        }
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        setDetails(request, authenticationToken);

        return this.getAuthenticationManager().authenticate(authenticationToken);
    }
}
